package com.samnative.pineapple.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.shashank.sony.fancytoastlib.FancyToast;
import com.samnative.pineapple.entity.UserModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.MD5Util;
import com.samnative.pineapple.utils.TimeCount;
import com.samnative.pineapple.utils.ViewHelper;
import com.samnative.pineapple.value.Config;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * 验证手机号（找回密码，修改密码，修改手机号等都要经过此页面验证）
 * Created by Wy on 2018/4/25.
 */

public class PasswordLoginVerityActivity extends BaseActivity implements View.OnClickListener, TimeCount.ITimeCountListener {

    public static PasswordLoginVerityActivity instance = null;

    /**
     * 获取验证码
     */
    private TextView tvGetVerity;

    /**
     * 用户输入的手机号
     */
    private EditText etPhone;

    /**
     * 验证码
     */
    private EditText etVerityCode;
    /**
     * 定时间器
     */
    private TimeCount mTimeCount;

    /**
     * 手机号
     */
    private String mobile;
    /**
     * 验证码
     */
    private String code;

    /**
     * 1 : 设置/修改登录密码 ， 2：找回登录密码 , 3 :修改手机号, 4:修改支付密码
     */
    private int type = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_find_loginpassword;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        instance = this;

        type = getIntent().getIntExtra("type", 1);

        find(R.id.rl_back).setOnClickListener(this);
        find(R.id.tv_sure).setOnClickListener(this);

        tvGetVerity = find(R.id.tv_get_verity);
        tvGetVerity.setOnClickListener(this);

        etVerityCode = find(R.id.et_verity_code);
        etPhone = find(R.id.et_phone);
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.setTimerCountListener(this);

        if (type == 1 || type == 3 || type == 4) {
            try {
                UserModel userModel = AppPrefer.getUserModel(mContext);
                etPhone.setText(userModel.getData().getUsername() + "");
                etPhone.setEnabled(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_sure:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                } else if (etVerityCode.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.verify_input_tips), FancyToast.WARNING, false);
                } else {
                    mobile = etPhone.getText().toString();
                    code = etVerityCode.getText().toString();

                    if (type == 1 || type == 2) {
                        validloginpwd();
                    } else if (type == 3) {
                        validMobile();
                    } else if (type == 4) {
                        validPaypwd();
                    }
                }
                break;
            case R.id.tv_get_verity:
                mobile = etPhone.getText().toString();
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                } else {
                    requestCode();
                }
                break;
            default:

        }
    }

    @Override
    public void finish() {
        super.finish();
        try {
            ViewHelper.hideKeyboard(this, etVerityCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取验证码
     */
    private void requestCode() {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("devicenumber", Config._uuid);
        map.put("privatekey", MD5Util.getMD5Str(mobile + Config._API_KEY));

        if (type == 1 || type == 2) {
            map.put("sendType", "update_loginpwd_");
        } else if (type == 3) {
            map.put("sendType", "update_phone_");
        } else if (type == 4) {
            map.put("sendType", "update_pay_");
        }
        map.put("_apiname", "user.public.sendvalicode");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                mTimeCount.start();
                tvGetVerity.setEnabled(false);
                tvGetVerity.setOnClickListener(null);
                FancyToast.showToast(mContext, getString(R.string.verify_send_success), FancyToast.INFO, false);
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });
    }


    /**
     * 找回，修改登录密码的验证码，验证后跳转设置登录密码的页面
     */
    private void validloginpwd() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", mobile);
        map.put("valicode", MD5Util.getMD5Str(code + Config._API_KEY));
        map.put("_apiname", "user.user.validloginpwd");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
                    JSONObject subJson = result
                            .getJSONObject("data");
                    String encrypt = subJson.getString("encrypt");
                    startActivity(new Intent().putExtra("type", type)
                            .putExtra("encrypt", encrypt)
                            .putExtra("mobile", mobile)
                            .setClass(mContext, PasswordLoginSetActivity.class));

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 修改手机号的验证码，验证后跳转设置手机号页面
     */
    public void validMobile() {
        String code = etVerityCode.getText().toString();
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("mobile", mobile);
        map.put("sourcetype", "1");
        map.put("valicode", MD5Util.getMD5Str(code + Config._API_KEY));
        map.put("_apiname", "user.user.validmobile");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
                    JSONObject data = result.getJSONObject("data");
                    String encrypt = data.getString("encrypt");
                    String sourcetype = data.getString("sourcetype");

                    Intent intent = new Intent(mContext,
                            SetMobileActivity.class);
                    intent.putExtra("encrypt", encrypt);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    /**
     * 修改支付密码的验证码，验证后跳转设置登录密码的页面
     */
    private void validPaypwd() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", mobile);
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("valicode", MD5Util.getMD5Str(code + Config._API_KEY));
        map.put("_apiname", "user.user.validPhonePay");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
//                    JSONObject subJson = result
//                            .getJSONObject("data");
//                    String encrypt = subJson.getString("encrypt");
                    startActivity(new Intent().putExtra("type", type)
//                            .putExtra("encrypt", encrypt)
                            .putExtra("mobile", mobile)
                            .setClass(mContext, PasswordPaySetActivity.class));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void onTick(long millisUntilFinished) {
        tvGetVerity.setText((millisUntilFinished / 1000) + getString(R.string.verify_confirm));
        tvGetVerity.setEnabled(false);
    }

    @Override
    public void onFinish() {
        tvGetVerity.setText(getString(R.string.verify_send_again));
        tvGetVerity.setEnabled(true);
        tvGetVerity.setOnClickListener(this);
    }

}
